﻿using AutoMapper;
using MediatR;
using Production.CommonLib.Models;
using Production.DomainLib.AggregatesModel.TechnologyAggregate;
using Swimj.CommonLib.Base;

namespace Production.ApplicationLib.Command
{
    public class CreateTechnologyCommand : TechnologyEditRequestDto, IRequest<Result<TechnologyInfoResponseDto>>
    {
    }

    public class
        CreateTechnologyCommandHandler : IRequestHandler<CreateTechnologyCommand, Result<TechnologyInfoResponseDto>>
    {
        private readonly ITechnologyRepository _technologyRepository;
        private readonly IMapper _mapper;

        public CreateTechnologyCommandHandler(ITechnologyRepository technologyRepository,
            IMapper mapper)
        {
            _technologyRepository = technologyRepository;
            _mapper = mapper;
        }

        public async Task<Result<TechnologyInfoResponseDto>> Handle(CreateTechnologyCommand request,
            CancellationToken cancellationToken)
        {
            var technology = new Technology(request.Code, request.Name, request.Quality,
                request.StandardBom.Id, request.StandardBom.Code, request.StandardBom.Name,
                request.Description);
            _technologyRepository.Add(technology);

            if (request.Items.Count > 0)
            {
                foreach (var item in request.Items)
                {
                    technology.AddItem(item.ProcessId, item.ProcessCode, item.ProcessName, item.Sort, item.TakeTime);
                }
            }

            await _technologyRepository.UnitOfWork.SaveEntitiesAsync(cancellationToken);

            return await Result<TechnologyInfoResponseDto>.SuccessAsync(
                _mapper.Map<TechnologyInfoResponseDto>(technology));
        }
    }
}